package com.mc.fastkit.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.mc.fastkit.ext.cast
import java.lang.reflect.ParameterizedType

/**
 * BaseVMFragment
 * @author: MasterChan
 * @date: 2024-04-08 14:46
 */
abstract class BaseVMFragment<T : ViewBinding, V : BaseViewModel> : BaseVBFragment<T>() {

    protected open val isShareViewModel = true
    protected open val viewModel by lazy { generateViewModel() }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        lifecycle.addObserver(viewModel)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    protected open fun generateViewModel(): V {
        var superClass = javaClass.genericSuperclass
        while (superClass !is ParameterizedType) {
            superClass = (superClass as Class<*>).genericSuperclass
        }
        val vm = superClass.actualTypeArguments[1].cast<Class<V>>()
        return if (isShareViewModel) {
            ViewModelProvider(requireActivity(), defaultViewModelProviderFactory)[vm]
        } else {
            ViewModelProvider(this)[vm]
        }
    }
}